﻿using Mengsk.ProxyDelivery.App.Domain;
using Mengsk.ProxyDelivery.App.Service;
using Mengsk.ProxyDelivery.Domain;
using Mengsk.ProxyDelivery.Service;
using Mengsk.ProxyDelivery.Utls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Mengsk.ProxyDelivery.App.UI.Order
{
    /// <summary>
    /// Interaction logic for OrderReturnOutUserControl.xaml
    /// </summary>
    public partial class OrderReturnOutUserControl : UserControl, IPlugin
    {
        private bool myLoad = false;

        private System.Collections.ObjectModel.ObservableCollection<OrderChangeOutViewModel> orderChanges = new System.Collections.ObjectModel.ObservableCollection<OrderChangeOutViewModel>();
        private OrderChangeService orderChangeService = ServiceContainer.GetService<OrderChangeService>();

        public string Title
        {
            get { return "退货出单"; }
        }

        public Control UIControl
        {
            get { return this; }
        }

        public OrderReturnOutUserControl()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (this.myLoad)
            {
                return;
            }
            this.dgvItems.ItemsSource = orderChanges;
            this.orderChanges.CollectionChanged += orderChanges_CollectionChanged;
        }

        void orderChanges_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            this.tbCount.Text = string.Format("当前共:{0}条退货记录,共:{1}双鞋子", this.orderChanges.Count, this.orderChanges.Select(obj => obj.OrderChange.Count).Sum());
        }

        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OrderChangeOutViewModel order = (e.Source as Hyperlink).DataContext as OrderChangeOutViewModel;
                if (order == null)
                {
                    return;
                }
                this.orderChanges.Remove(order);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void tbOrderChangeId_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter)
            {
                return;
            }

            try
            {
                int id = int.Parse(this.tbOrderChangeId.Text.Trim().ToUpper());
                if (this.orderChanges.FirstOrDefault(obj => obj.OrderChange.Id == id) != null)
                {
                    Speaker.Speak("已存在");
                    return;
                }
                OrderChange oc = this.orderChangeService.GetById(id);
                if (oc == null)
                {
                    Speaker.Speak("未找到");
                    return;
                }

                if (oc.State != OrderChangeState.WaitToVendor && oc.State != OrderChangeState.ToVendorIng && oc.State != OrderChangeState.ToVendorFail && oc.State != OrderChangeState.Reject)
                {
                    Speaker.Speak("状态不对");
                    return;
                }

                this.orderChanges.Add(new OrderChangeOutViewModel { OrderChange = oc });

                Speaker.Speak("已接受");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.tbOrderChangeId.Text = "";
            }
        }

        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {
            if (this.orderChanges.Count < 1)
            {
                MessageBox.Show("没有需要打印的数据");
                return;
            }

            try
            {
                string printer = LocalConfigService.GetValue("APP_NORMALPRINTER", "");
                if (string.IsNullOrWhiteSpace(printer))
                {
                    throw new Exception("请在系统配置里面，配置要使用的打印机");
                }
                string message = string.Format("是否打印:\n打印机:{0}\n打印数量:{1}", printer, this.orderChanges.Count);
                if (MessageBox.Show(message, "提示", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
                {
                    return;
                }
                var pd = PrintUtil.GetPrinter(printer);
                VendorService vs = ServiceContainer.GetService<VendorService>();
                Domain.RefundToVendorDocument goodsCountDoc = new RefundToVendorDocument();

                List<GoodsCount> counts = new List<GoodsCount>();
                foreach (var item in this.orderChanges)
                {
                    string[] infos = item.OrderChange.GoodsInfo.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
                    if (infos.Length < 4)
                    {
                        MessageBox.Show("退货信息不正确，请检查:" + item.OrderChange.Id);
                        continue;
                    }
                    var vendor = vs.GetByField("Name", infos[0]);
                    if (vendor == null)
                    {
                        vendor = vs.GetByField("Name", infos[0] + infos[1]);
                    }

                    if (vendor == null)
                    {
                        MessageBox.Show("退货信息厂家找不到，请检查:" + item.OrderChange.Id);
                        continue;
                    }

                    GoodsCount count = null;
                    if (infos.Length >= 5)
                    {
                        count = counts.FirstOrDefault(obj => obj.Vendor == VendorService.FormatVendorName(infos[0]) && obj.Number == infos[1] && obj.Edtion == infos[2] && obj.Color == infos[3] && obj.Size == infos[4]);
                    }
                    else
                    {
                        count = counts.FirstOrDefault(obj => obj.Vendor == VendorService.FormatVendorName(infos[0]) && obj.Number == infos[1] && obj.Color == infos[2] && obj.Size == infos[3]);
                    }


                    if (count == null)
                    {
                        count = new GoodsCount
                        {
                            Vendor = infos[0].Trim(),
                            Number = infos[1].Trim(),
                            Market = "1",
                            Money = (int)(item.OrderChange.GoodsMoney / item.OrderChange.Count),
                            Count = 0,
                            PayTime = item.OrderChange.ProcessTime,
                        };

                        if (infos.Length >= 5)
                        {
                            count.Edtion = infos[2].Trim();
                            count.Color = infos[3].Trim();
                            count.Size = infos[4].Trim();
                        }
                        else
                        {
                            count.Edtion = "";
                            count.Color = infos[2].Trim();
                            count.Size = infos[3].Trim();
                        }

                        //解析门牌，街道
                        string address = vendor.MarketAddress;
                        string door = VendorService.FindDoor(address);
                        string area = VendorService.FindAreaOrStreet(address, "区");
                        string street = VendorService.FindAreaOrStreet(address, "街");
                        count.Address = string.Format("{0}-{1}-{2}", area, door, street);
                        count.Vendor = VendorService.FormatVendorName(count.Vendor);

                        int iArea = 0, iDoor = 0, iStreet = 0;

                        int.TryParse(area, out iArea);
                        int.TryParse(door, out iDoor);
                        int.TryParse(street, out iStreet);

                        count.Area = iArea;
                        count.Door = iDoor;
                        count.Street = iStreet;
                        counts.Add(count);
                    }
                    foreach (var c in counts.Where(obj => obj.Vendor == count.Vendor && obj.Number == count.Number && obj.Edtion == count.Edtion))
                    {
                        //取消最大金额值
                        if (c.Money < count.Money)
                        {
                            c.Money = count.Money;
                        }
                        else
                        {
                            count.Money = c.Money;
                        }
                    }

                    if (count.PayTime >= item.OrderChange.ProcessTime)
                    {
                        count.PayTime = item.OrderChange.ProcessTime;
                    }

                    count.Count += item.OrderChange.Count;
                }

                //排序
                counts.Sort();//区
                counts.Sort();//连
                counts.Sort();//门
                counts.Sort();//街
                counts.Sort();//货号
                counts.Sort();//版本
                counts.Sort();//颜色
                counts.Sort();//尺码

                goodsCountDoc.PageSize = new Size(793, 1122.24);
                goodsCountDoc.SetGoodsCount(counts.ToArray());
                pd.PrintDocument(goodsCountDoc, "退货统计");
                foreach (var item in this.orderChanges)
                {
                    this.orderChangeService.MarkToVendoring(item.OrderChange.Id);
                }
                MessageBox.Show("打印完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message+Environment.NewLine+ex.StackTrace, "打印出错");
            }
        }

        private void btnMark_Click(object sender, RoutedEventArgs e)
        {
            if (this.orderChanges.Count < 1)
            {
                MessageBox.Show("没有需要打印的数据");
                return;
            }

            try
            {
                foreach (var item in this.orderChanges)
                {
                    this.orderChangeService.MarkToVendoring(item.OrderChange.Id);
                }
                MessageBox.Show("已完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("清空所有", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
            {
                return;
            }

            this.orderChanges.Clear();
        }
    }
}
